import 'package:flutter/material.dart';

///加载网络图片 封装失败图片和圆角
class ImageNetWidget extends StatefulWidget {
  ImageNetWidget(
      {Key? key,
      required this.url,
      this.w,
      this.h,
      this.defImagePath = "assets/images/img_load_err.png",
      this.allRadius = 0,
      this.botLeftRadius = 0,
      this.botRightRadius = 0,
      this.topLeftRadius = 0,
      this.topRightRadius = 0})
      : super(key: key);

  final String url;
  final double? w;
  final double? h;
  final String? defImagePath;

  final double allRadius;

  double topLeftRadius;
  double topRightRadius;
  double botLeftRadius;
  double botRightRadius;

  @override
  State<StatefulWidget> createState() {
    return _StateImageWidget();
  }
}

class _StateImageWidget extends State<ImageNetWidget> {
  late Image _image;

  @override
  void initState() {
    super.initState();
    _image = Image.network(
      widget.url,
      width: widget.w,
      height: widget.h,
      fit: BoxFit.fill,
    );
    var resolve = _image.image.resolve(ImageConfiguration.empty);
    resolve.addListener(ImageStreamListener((_, __) {
      //加载成功
    }, onError: (dynamic exception, stackTrace) {
      //加载失败
      setState(() {
        _image = Image.asset(
          widget.defImagePath!,
          width: widget.w,
          height: widget.h,
        );
      });
    }));
  }

  @override
  Widget build(BuildContext context) {
    if (widget.allRadius != 0) {
      widget.botLeftRadius = widget.allRadius;
      widget.botRightRadius = widget.allRadius;
      widget.topRightRadius = widget.allRadius;
      widget.topLeftRadius = widget.allRadius;
    }

    return ClipRRect(
        borderRadius: BorderRadius.only(
            bottomLeft: Radius.circular(widget.botLeftRadius),
            topLeft: Radius.circular(widget.topLeftRadius),
            topRight: Radius.circular(widget.topRightRadius),
            bottomRight: Radius.circular(widget.botRightRadius)),
        child: _image);
  }
}
